import 'dart:async';
import '../../core/storage/storage_service.dart';
import '../../core/utils/logger.dart';

class AuthService {
  static AuthService? _instance;
  static AuthService get instance => _instance ??= AuthService._internal();
  
  final StorageService _storageService = StorageService.instance;
  
  String? _token;
  String? _refreshToken;
  DateTime? _tokenExpiry;
  Map<String, dynamic>? _userInfo;
  
  final StreamController<bool> _authStateController = StreamController<bool>.broadcast();
  
  AuthService._internal();

  // 认证状态流
  Stream<bool> get authStateStream => _authStateController.stream;

  // 获取当前认证状态
  bool get isAuthenticated => _token != null && !_isTokenExpired();

  // 获取用户信息
  Map<String, dynamic>? get userInfo => _userInfo;

  // 获取Token
  String? getToken() => _token;

  // 获取刷新Token
  String? getRefreshToken() => _refreshToken;

  // 初始化认证服务
  Future<void> init() async {
    try {
      await _loadTokenFromStorage();
      AppLogger.info('Auth service initialized');
    } catch (e) {
      AppLogger.error('Failed to initialize auth service', e);
    }
  }

  // 从存储中加载Token
  Future<void> _loadTokenFromStorage() async {
    try {
      _token = _storageService.getUserPreference<String>('auth_token');
      _refreshToken = _storageService.getUserPreference<String>('auth_refresh_token');
      
      final expiryTimestamp = _storageService.getUserPreference<int>('auth_token_expiry');
      if (expiryTimestamp != null) {
        _tokenExpiry = DateTime.fromMillisecondsSinceEpoch(expiryTimestamp);
      }
      
      _userInfo = _storageService.getUserPreference<Map<String, dynamic>>('auth_user_info');
      
      if (_token != null) {
        if (_isTokenExpired()) {
          AppLogger.info('Token expired, clearing auth data');
          await _clearAuthData();
        } else {
          AppLogger.info('Token loaded from storage');
          _authStateController.add(true);
        }
      }
    } catch (e) {
      AppLogger.error('Failed to load token from storage', e);
    }
  }

  // 保存Token到存储
  Future<void> saveToken(String token, {
    String? refreshToken,
    DateTime? expiry,
    Map<String, dynamic>? userInfo,
  }) async {
    try {
      _token = token;
      _refreshToken = refreshToken;
      _tokenExpiry = expiry;
      _userInfo = userInfo;

      await _storageService.setUserPreference('auth_token', token);
      
      if (refreshToken != null) {
        await _storageService.setUserPreference('auth_refresh_token', refreshToken);
      }
      
      if (expiry != null) {
        await _storageService.setUserPreference('auth_token_expiry', expiry.millisecondsSinceEpoch);
      }
      
      if (userInfo != null) {
        await _storageService.setUserPreference('auth_user_info', userInfo);
      }

      AppLogger.info('Token saved to storage');
      _authStateController.add(true);
    } catch (e) {
      AppLogger.error('Failed to save token to storage', e);
    }
  }

  // 更新用户信息
  Future<void> updateUserInfo(Map<String, dynamic> userInfo) async {
    try {
      _userInfo = userInfo;
      await _storageService.setUserPreference('auth_user_info', userInfo);
      AppLogger.info('User info updated');
    } catch (e) {
      AppLogger.error('Failed to update user info', e);
    }
  }

  // 清除Token
  Future<void> clearToken() async {
    try {
      await _clearAuthData();
      AppLogger.info('Token cleared');
      _authStateController.add(false);
    } catch (e) {
      AppLogger.error('Failed to clear token', e);
    }
  }

  // 清除认证数据
  Future<void> _clearAuthData() async {
    _token = null;
    _refreshToken = null;
    _tokenExpiry = null;
    _userInfo = null;

    await Future.wait([
      _storageService.removeUserPreference('auth_token'),
      _storageService.removeUserPreference('auth_refresh_token'),
      _storageService.removeUserPreference('auth_token_expiry'),
      _storageService.removeUserPreference('auth_user_info'),
    ]);
  }

  // 检查Token是否过期
  bool _isTokenExpired() {
    if (_tokenExpiry == null) return false;
    return DateTime.now().isAfter(_tokenExpiry!);
  }

  // 检查Token是否即将过期 (5分钟内)
  bool isTokenExpiringSoon() {
    if (_tokenExpiry == null) return false;
    final fiveMinutesFromNow = DateTime.now().add(const Duration(minutes: 5));
    return _tokenExpiry!.isBefore(fiveMinutesFromNow);
  }

  // 获取Token剩余时间
  Duration? getTokenRemainingTime() {
    if (_tokenExpiry == null) return null;
    final now = DateTime.now();
    if (now.isAfter(_tokenExpiry!)) return Duration.zero;
    return _tokenExpiry!.difference(now);
  }

  // 刷新Token
  Future<bool> refreshToken() async {
    try {
      if (_refreshToken == null) {
        AppLogger.warning('No refresh token available');
        return false;
      }

      // 这里应该调用API刷新Token
      // 示例代码：
      // final result = await _apiClient.refreshToken(_refreshToken!);
      // if (result.isSuccess) {
      //   await saveToken(
      //     result.data.accessToken,
      //     refreshToken: result.data.refreshToken,
      //     expiry: result.data.expiry,
      //   );
      //   return true;
      // }

      AppLogger.info('Token refreshed successfully');
      return true;
    } catch (e) {
      AppLogger.error('Failed to refresh token', e);
      return false;
    }
  }

  // 自动刷新Token
  Future<void> autoRefreshToken() async {
    if (isTokenExpiringSoon()) {
      AppLogger.info('Token expiring soon, attempting to refresh');
      final success = await refreshToken();
      if (!success) {
        AppLogger.warning('Failed to refresh token, clearing auth data');
        await clearToken();
      }
    }
  }

  // 登录
  Future<bool> login(String username, String password) async {
    try {
      // 这里应该调用登录API
      // 示例代码：
      // final result = await _apiClient.login(username, password);
      // if (result.isSuccess) {
      //   await saveToken(
      //     result.data.accessToken,
      //     refreshToken: result.data.refreshToken,
      //     expiry: result.data.expiry,
      //     userInfo: result.data.userInfo,
      //   );
      //   return true;
      // }

      AppLogger.info('Login successful');
      return true;
    } catch (e) {
      AppLogger.error('Login failed', e);
      return false;
    }
  }

  // 登出
  Future<void> logout() async {
    try {
      // 这里应该调用登出API
      // await _apiClient.logout();
      
      await clearToken();
      AppLogger.info('Logout successful');
    } catch (e) {
      AppLogger.error('Logout failed', e);
    }
  }

  // 获取用户权限
  List<String> getUserPermissions() {
    if (_userInfo == null) return [];
    final permissions = _userInfo!['permissions'] as List<dynamic>?;
    return permissions?.map((p) => p.toString()).toList() ?? [];
  }

  // 检查用户权限
  bool hasPermission(String permission) {
    final permissions = getUserPermissions();
    return permissions.contains(permission);
  }

  // 检查多个权限
  bool hasAnyPermission(List<String> permissions) {
    final userPermissions = getUserPermissions();
    return permissions.any((p) => userPermissions.contains(p));
  }

  // 检查所有权限
  bool hasAllPermissions(List<String> permissions) {
    final userPermissions = getUserPermissions();
    return permissions.every((p) => userPermissions.contains(p));
  }

  // 获取用户角色
  List<String> getUserRoles() {
    if (_userInfo == null) return [];
    final roles = _userInfo!['roles'] as List<dynamic>?;
    return roles?.map((r) => r.toString()).toList() ?? [];
  }

  // 检查用户角色
  bool hasRole(String role) {
    final roles = getUserRoles();
    return roles.contains(role);
  }

  // 获取用户ID
  String? getUserId() {
    return _userInfo?['id']?.toString();
  }

  // 获取用户名
  String? getUsername() {
    return _userInfo?['username']?.toString();
  }

  // 获取用户邮箱
  String? getUserEmail() {
    return _userInfo?['email']?.toString();
  }

  // 获取用户头像
  String? getUserAvatar() {
    return _userInfo?['avatar']?.toString();
  }

  // 启动自动刷新定时器
  Timer? _autoRefreshTimer;
  
  void startAutoRefreshTimer() {
    _autoRefreshTimer?.cancel();
    _autoRefreshTimer = Timer.periodic(const Duration(minutes: 5), (timer) {
      autoRefreshToken();
    });
    AppLogger.info('Auto refresh timer started');
  }

  // 停止自动刷新定时器
  void stopAutoRefreshTimer() {
    _autoRefreshTimer?.cancel();
    _autoRefreshTimer = null;
    AppLogger.info('Auto refresh timer stopped');
  }

  // 释放资源
  void dispose() {
    _authStateController.close();
    stopAutoRefreshTimer();
    AppLogger.info('Auth service disposed');
  }
}